﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;

namespace CommonUtils
{
    /// <summary>
    /// 类扩展
    /// </summary>
    public static partial class Extension
    {
        public static void For(this int length, Action<int> action)
        {
            for (int index = 0; index < length; index++)
                action.Invoke(index);
        }

        /// <summary>
        /// 获取内存地址
        /// </summary>
        public static string GetMemoryAddress(this object obj)
        {
            GCHandle hander = GCHandle.Alloc(obj);
            IntPtr pin = GCHandle.ToIntPtr(hander);
            return pin.ToString();
        }

        /// <summary>
        /// 相同数据结构不同类之间转换，同种类或者继承类请用As
        /// </summary>
        public static T To<T>(this object item)
        => JsonUtil.Deserialize<T>(item.ToJson(true));

        /// <summary>
        /// 用于类的深复制
        /// </summary>
        public static T Copy<T>(T obj)
        => JsonUtil.Deserialize<T>(obj.ToJson(true));

        /// <summary>
        /// 拆箱或者父类转子类(前提是该父类本身就是子类，只是以父类形式存在)
        /// </summary>
        public static T As<T>(this object item)
        => (T)item;

        public static void Print(this object value)
        => LogUtil.PrintInfo(value);

        public static void PrintJson(this object value)
        => LogUtil.InfoJson(value);

        public static void Warn(this object value)
        => LogUtil.Warn(value);

        /// <summary>
        /// 选择堆栈数量
        /// </summary>
        public static string Take(this StackTrace stack, int count)
        {
            var lines = stack.ToString().GetLines();
            return lines.Take(count).JoinToText();
        }
    }
}
